package com.amigo.online.provider.user.service.impl;


import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;

import com.amigo.online.common.base.message.entity.MIMCJsonResponse;
import com.amigo.online.common.core.response.Result;
import com.amigo.online.common.param.dto.group.*;
import com.amigo.online.provider.user.common.CommonCount;
import com.amigo.online.provider.user.model.entity.GroupNotice;
import com.amigo.online.provider.user.mongo.dao.GroupDao;
import com.amigo.online.provider.user.mongo.dao.GroupRepository;
import com.amigo.online.provider.user.mongo.entity.GroupEntity;
import com.amigo.online.provider.user.figen.MessageFeignService;
import com.amigo.online.provider.user.util.IMGroupUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.geo.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.amigo.online.common.core.response.StatusCode;
import com.amigo.online.common.param.RedisKey;
import com.amigo.online.common.param.result.GroupInfo;
import com.amigo.online.common.param.result.GroupListInfo;
import com.amigo.online.common.param.result.GroupUserInfo;
import com.amigo.online.common.param.result.PullableFriendsInfo;
import com.amigo.online.common.param.result.UserInfo;
import com.amigo.online.provider.user.common.GlobalController;
import com.amigo.online.provider.user.common.RwRedisService;
import com.amigo.online.provider.user.exception.UserException;
import com.amigo.online.provider.user.mapper.GroupMapper;
import com.amigo.online.provider.user.mapper.GroupMemberMapper;
import com.amigo.online.provider.user.mapper.UserMapper;
import com.amigo.online.provider.user.model.entity.Group;
import com.amigo.online.provider.user.model.entity.GroupMember;
import com.amigo.online.provider.user.model.entity.User;
import com.amigo.online.provider.user.service.FollowService;
import com.amigo.online.provider.user.service.GroupService;
import com.amigo.online.provider.user.service.UserService;

import tk.mybatis.mapper.entity.Example;

/**
 * @author kml
 */
@Service
@SuppressWarnings({"unused", "rawtypes"})
@Slf4j
public class GroupServiceImpl implements GroupService {

    @Autowired
    MessageFeignService messageFeignService;
    @Autowired
    GroupMapper groupMapper;

    @Autowired
    GroupMemberMapper groupMemberMapper;

    @Autowired
    UserService userService;

    @Autowired
    UserMapper userMapper;

    @Autowired
    private RwRedisService rwRedisService;

    @Autowired
    GroupRepository groupRepository;

    @Autowired
    @Qualifier("imRedisTemplate")
    private RedisTemplate<String, Object> imRedisTemplate;

    @Autowired
    private GroupDao groupDao;

    @Autowired
    private FollowService followService;

    @Autowired
    @Qualifier("readMongoTemplate")
    MongoTemplate readMongoTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public GroupInfo newGroup(NewGroupDto dto) {
//        if (dto == null || dto.getMemberIds() == null || dto.getMemberIds().size() < 2) {
//            throw new UserException(StatusCode.BAD_REQUEST);
//        }
        UserInfo user = GlobalController.getNowUser();
        //群组表中插入群信息
        Group group = buildGroup(dto, user);
        if (groupMapper.insertSelective(group) <= 0) {
            throw new UserException(StatusCode.NEW_GROUP_FAILED);
        }

        //群组成员表中插入用户信息
        List<GroupMember> members = buildGroupMembers(dto.getMemberIds(), group);
        //判断群成员用户状态是否是正常，有不正常则创建群失败
        List<Long> ids = members.stream().map(e -> e.getUser_id()).collect(Collectors.toList());
        List<User> userList = userMapper.findByIdList(ids);
        if (userList.size() != ids.size() || groupMemberMapper.insertList(members) <= 0) {
            throw new UserException(StatusCode.NEW_GROUP_FAILED);
        }
        GroupInfo groupInfo = new GroupInfo();
        BeanUtils.copyProperties(dto, groupInfo);
        groupInfo.setGroupId(group.getId());
        groupInfo.setMemberNumber(dto.getMemberIds() == null ? 1 : dto.getMemberIds().size() + 1);
        groupInfo.setName(StringUtils.isBlank(dto.getName()) ? "" : dto.getName());
        groupInfo.setUserId(user.getId());

        group.setExamine(dto.getExamine());
        group.setName(groupInfo.getName());
        group.setLatitude(dto.getLatitude());
        group.setLongitude(dto.getLongitude());
        group.setInvisible(dto.getInvisible());
        group.setAvatar(dto.getAvatar());
        group.setUser_id(user.getId());
        group.setCreated_user_id(user.getId());
        group.setChecked_time(0L);
        group.setIntroduction(dto.getIntroduction());
        group.setStatus(1);
        group.setDisbanded(0);
        groupDao.insertGroup(group);

//        JSONObject groupJson = new JSONObject();
//        groupJson.put("id", group.getId());
//        groupJson.put("groupName", groupInfo.getName());
//        groupJson.put("groupAvatar", group.getAvatar() == null ? "" : group.getAvatar());
//        groupJson.put("hostId", user.getId());
//        List<JSONObject> memberList = new ArrayList<>();
//        for (User u : userList) {
//            JSONObject memberJson = new JSONObject();
//            memberJson.put("userId", u.getId());
//            memberJson.put("userAvatar", u.getAvatar());
//            memberJson.put("sex", u.getSex());
//            memberJson.put("isManager", u.getId().equals(user.getId()));
//            memberJson.put("username", u.getNickname());
//            memberList.add(memberJson);
//        }
//        groupJson.put("members", memberList);
//        String group_redis_key = RedisKey.USER_GROUP_INFO_KEY + group.getId();
//        rwRedisService.hputAll(group_redis_key, groupJson);

        return groupInfo;
    }

    private Group buildGroup(NewGroupDto dto, UserInfo user) {
        Group group = new Group();
        group.setLatitude(dto.getLatitude());
        group.setLongitude(dto.getLongitude());
        group.setExamine(dto.getExamine());
        group.setUser_id(user.getId());
        group.setCreated_user_id(user.getId());
        group.setName(dto.getName());
        long nowSeconds = System.currentTimeMillis() / 1000;
        group.setCreatedTime(nowSeconds);
        group.setUpdated_time(0L);
        group.setType(1);
        group.setExamine(0);
        group.setAddress(dto.getAddress());
        group.setIntroduction(dto.getIntroduction());
        group.setInvisible(dto.getInvisible());
        return group;
    }

    private List<GroupMember> buildGroupMembers(List<Long> ids, Group group) {
        List<GroupMember> members = new ArrayList<>();
        if (ids == null) {
            ids = new ArrayList<>();
        }
        long nowSeconds = Instant.now().getEpochSecond();
        //群主
        if (group != null && group.getUser_id() != null) {
            GroupMember groupMember = new GroupMember();
            groupMember.setGroup_id(group.getId());
            groupMember.setHost(1);
            //群主id
            groupMember.setUser_id(group.getUser_id());
            groupMember.setManager(1);
            groupMember.setBaned(0);
            groupMember.setRemind(1);
            groupMember.setCreatedTime(nowSeconds);
            groupMember.setUpdated_time(0L);
            groupMember.setQuit(0);
            groupMember.setIs_allow(1);
            groupMember.setQuit_time(0L);
            members.add(groupMember);
        }
        //普通成员
        for (Long id : ids) {
            GroupMember groupGeneralMember = new GroupMember();
            groupGeneralMember.setGroup_id(group.getId());
            groupGeneralMember.setHost(1);
            groupGeneralMember.setManager(0);
            groupGeneralMember.setBaned(0);
            groupGeneralMember.setRemind(1);
            groupGeneralMember.setIs_allow(1);
            groupGeneralMember.setCreatedTime(nowSeconds);
            groupGeneralMember.setUpdated_time(nowSeconds);
            groupGeneralMember.setQuit(0);
            groupGeneralMember.setQuit_time(0L);
            groupGeneralMember.setHost(0);
            groupGeneralMember.setUser_id(id);
            groupGeneralMember.setManager(0);
            members.add(groupGeneralMember);
        }
        return members;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean quitGroup(QuitGroupDto dto) {
        String group_redis_key = RedisKey.USER_GROUP_INFO_KEY + dto.getGroupId();
        UserInfo user = GlobalController.getNowUser();
        boolean isHost = groupMapper.getCountByHostId(user.getId(), dto.getGroupId()) > 0;
        long currentTime = System.currentTimeMillis() / 1000;
        //自己退群
        if (dto.getType() == 1) {
            //判断是否管理员
            //是管理员
            if (isHost) {
                //群主不能退群
                throw new UserException(StatusCode.MASTER_CANT_QUIT_GROUP);
//                //获取群主之外第二个加入群的人
//                Long secondId = groupMemberMapper.getSecondMemberId(dto.getGroupId());
//                if (secondId != null) {
//                    //把group表的群主换掉
//                    groupMapper.changeGroupHost(dto.getGroupId(), secondId, currentTime);
//                    //把group_member表的群主换掉
//                    groupMemberMapper.changeGroupMemberHost(dto.getGroupId(), secondId, currentTime);
//                    //把redis中的群主ID换掉
////                    rwRedisService.hput(group_redis_key, "id", secondId);
//                }
            }

        } else {    //管理员踢人
            if (dto.getUserId() == null) {
                throw new UserException(StatusCode.BAD_REQUEST);
            }
            //此人不是管理员
            if (groupMapper.getCountByHostId(user.getId(), dto.getGroupId()) <= 0) {
                throw new UserException(StatusCode.FORBIDDEN);
            }
        }
        //退出群
        ResponseEntity<MIMCJsonResponse> responseResponseEntity = IMGroupUtil.quitGroupMessage(dto.getGroupId(), dto.getUserId());
        if(responseResponseEntity.getBody().getCode()!=200){
            return false;
        }
        GroupMember groupMember = new GroupMember();
        groupMember.setGroup_id(dto.getGroupId());
        groupMember.setUser_id(dto.getType() == 1 ? user.getId() : dto.getUserId());
        groupMember.setQuit(dto.getType() == 1 ? 1 : 2);
        groupMember.setQuit_time(currentTime);
        groupMember.setManager(0);
        groupMember.setHost(0);
        groupMemberMapper.updateQuitByGroupIdAndUserId(groupMember);

        //更新reids
//        List memberList = (List) rwRedisService.hget(group_redis_key, "members");
//        if (memberList != null) {
//            //把退出去的人移除
//            for (Object object : memberList) {
//                if (((JSONObject) object).get("userId").equals(groupMember.getUser_id())) {
//                    memberList.remove(object);
//                    break;
//                }
//            }
//            rwRedisService.hput(group_redis_key, "members", memberList);
//        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean editGroup(EditGroupDto dto) {
        if (dto == null || dto.getId() == null ||
                (dto.getIsTop() == null && dto.getName() == null && dto.getRemind() == null)) {
            throw new UserException(StatusCode.BAD_REQUEST);
        }
        //修改群的内容
        if (dto.getName() != null) {
            ResponseEntity<MIMCJsonResponse> responseResponseEntity =  IMGroupUtil.updateGroupInfo(dto.getId(), dto.getName(),null,null);
            if(responseResponseEntity.getBody().getCode()!=200){
                return false;
            }
            Group group = new Group();
            group.setId(dto.getId());
            group.setName(dto.getName());
            groupMapper.updateByPrimaryKeySelective(group);

            //更新redis
//            String group_redis_key = RedisKey.USER_GROUP_INFO_KEY + dto.getId();
//            rwRedisService.hput(group_redis_key, "groupName", dto.getName());
            return true;
        }
        //群成员修改消息免打扰
        if (dto.getRemind() != null) {
            GroupMember groupMember = new GroupMember();
            groupMember.setUser_id(dto.getUserId());
            groupMember.setGroup_id(dto.getId());
            groupMember.setRemind(dto.getRemind());
            groupMemberMapper.updateRemind(groupMember);
            return true;
        }
        return false;
    }

    @Override
    public List<PullableFriendsInfo> getPullableFriends(Long groupId) {
        if (groupId == null) {
            throw new UserException(StatusCode.BAD_REQUEST);
        }
        UserInfo u = GlobalController.getNowUser();
        List<PullableFriendsInfo> list = new ArrayList<>();

        //获取好友列表
        List<UserInfo> friends = followService.getFriends();
        if (friends == null || friends.isEmpty()) {
            return list;
        }

        List<GroupMember> members = new ArrayList<>();
        //groupId 小于0的话则不需要标记已在群中的好友
        if (groupId >= 0) {
            //获取组的成员列表
            GroupMember record = new GroupMember();
            record.setGroup_id(groupId);
            record.setQuit(0);
            members = groupMemberMapper.select(record);
        }
        Set<Long> membersSet = members.stream().map(GroupMember::getUser_id).collect(Collectors.toSet());
        //在好友列表中标记出已在群中的好友
        for (UserInfo friend : friends) {
            if (friend != null) {
                PullableFriendsInfo pf = new PullableFriendsInfo();
                pf.setUserId(friend.getId());
                pf.setNickname(friend.getNickname());
                pf.setSex(friend.getSex());
                pf.setExisted(membersSet.contains(friend.getId()));
                pf.setAvatar(friend.getAvatar());
                list.add(pf);
            }
        }

        return list;
    }

    @SuppressWarnings("unchecked")
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addGroupMember(AddGroupMemberDto dto) {
        //判断群成员用户状态是否是正常，有不正常则添加群成员失败
        List<User> userList = userMapper.findByIdList(dto.getMemberIds());
        if (userList.size() != dto.getMemberIds().size()) {
            return false;
        }
        Result result = messageFeignService.invitation(dto);
        if(result.getMeta().getCode()!=200){
            return false;
        }
        Group group = new Group();
        group.setId(dto.getGroupId());
        List<GroupMember> members = buildGroupMembers(dto.getMemberIds(), group);

        //查询这批用户是否是已经存在群成员表中，如果已存在，把状态改成正常，如果不存在则插入
        List<Long> userIds = members.stream().map(GroupMember::getUser_id).collect(Collectors.toList());
        Map<String, Object> params = new HashMap<>(16);
        params.put("userIds", userIds);
        params.put("groupId", dto.getGroupId());

        //已经在群中并且 quit!=0 的，把状态改成正常 set quit = 0
        List<GroupMember> existedMembers = groupMemberMapper.selectExisted(params);
        if (existedMembers.size() > 0) {
            groupMemberMapper.batchUpdateStatusExisted(existedMembers);
        }

        //不在群中的，直接插入
        members.removeAll(existedMembers);
        int rs = 0;
        if (members.size() > 0) {
            rs = groupMemberMapper.insertList(members);
        }

        //把新加入的 成员加到redis
        if (rs > 0) {
            String group_redis_key = RedisKey.USER_GROUP_INFO_KEY + group.getId();
            List<JSONObject> newMemberList = new ArrayList<>();
            for (User u : userList) {
                JSONObject memberJson = new JSONObject();
                memberJson.put("userId", u.getId());
                memberJson.put("userAvatar", u.getAvatar());
                memberJson.put("sex", u.getSex());
                memberJson.put("isManager", false);
                memberJson.put("username", u.getNickname());
                newMemberList.add(memberJson);
            }
//            List memberList = (List) rwRedisService.hget(group_redis_key, "members");
//            if (memberList != null) {
//                memberList.addAll(newMemberList);
//                rwRedisService.hput(group_redis_key, "members", memberList);
//            }
        }
        //im离线数据数量修改
        String im_group_redis_key = dto.getGroupId() + "_tt_group_msg";
        //这个群的离线消息数量
        Integer count = (Integer) imRedisTemplate.opsForHash().get(im_group_redis_key, "count");
        for (Long memberId : dto.getMemberIds()) {
            //20261_10039_tt_user_group
            String key = memberId + "_" + dto.getGroupId() + "_tt_user_group";
            imRedisTemplate.opsForHash().put(key, "count", count);
        }

        return rs > 0 ? true : false;
    }

    @Override
    public GroupListInfo getMyGroup() {
        UserInfo userInfo = GlobalController.getNowUser();
        List<GroupInfo> groupList = groupMapper.getMyGroup(userInfo.getId());
        //查询出群组有多少成员
        List<Long> groupIds = groupList.stream().map(GroupInfo::getGroupId).collect(Collectors.toList());
        List<CommonCount> res = groupMemberMapper.getMembersCountByGroupIds(groupIds);
        Map<Long, Integer> groupMemberCountMap = res.stream().collect(Collectors.toMap(CommonCount::getId, CommonCount::getCount));
        List<GroupInfo> myCreate = new ArrayList<>();
        List<GroupInfo> myIn = new ArrayList<>();
        for (GroupInfo groupInfo : groupList) {
            Integer count = groupMemberCountMap.get(groupInfo.getGroupId());
            groupInfo.setMemberNumber(count == null ? 0 : count);
            if (userInfo.getId().equals(groupInfo.getCreatedUserId())) {
                myCreate.add(groupInfo);
            } else {
                myIn.add(groupInfo);
            }

        }
        return new GroupListInfo(myCreate, myIn);
    }

    @Override
    public List<GroupUserInfo> getMembersByGroupId(Long groupId, Integer page, Integer size) {
        Long offset = (long) (page - 1) * size;
        return groupMemberMapper.getMembersByGroupId(groupId, offset, size);
    }

    @Override
    public int getMembersCountByGroupId(Long groupId) {
        return groupMemberMapper.getMembersCountByGroupId(groupId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateGroup(UpdateGroupDto dto) {
        //修改IM信息
        Group group = new Group();
        BeanUtils.copyProperties(dto, group);
        group.setUpdated_time(Instant.now().getEpochSecond());
        ResponseEntity<MIMCJsonResponse> responseResponseEntity = IMGroupUtil.updateGroupInfo(dto.getId(),null,null,dto.getAvatar());
        if(responseResponseEntity.getBody().getCode()!=200){
            return "";
        }
        int rs = groupMapper.updateByPrimaryKeySelective(group);
        return rs > 0 ? dto.getAvatar() : "";
    }

    @Override
    public List<GroupInfo> nearbyGroup(Integer page, String lnt, String lat) {
        Long userId = GlobalController.getNowUser().getId();
        List<GroupInfo> groupList = new ArrayList<>();
        Double x = 0.00;
        Double y = 0.00;
        try {
            x = Double.parseDouble(lnt);
            y = Double.parseDouble(lat);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        //附近人可见
        int invisible = 0;

        GeoPage<GroupEntity> geoResults = groupRepository.findByLocNearAndInvisible(
                new Point(x, y),
                new Distance(25, Metrics.KILOMETERS),
                invisible,
                PageRequest.of(page-1, 10));
        List<GeoResult<GroupEntity>> rs = geoResults.getContent();
        log.info("获取数量:" + rs.size());
        for (GeoResult<GroupEntity> r : rs) {
            GroupEntity group = r.getContent();
            GroupInfo groupInfo = new GroupInfo();
            groupInfo.setGroupId(group.getId());
            groupInfo.setName(group.getName());
            groupInfo.setIntroduction(group.getIntroduction());
            groupInfo.setAddress(group.getAddress());
            groupInfo.setAddressName(group.getAddressName());
            groupInfo.setAvatar(group.getAvatar());
            groupInfo.setDistance(String.format("%.2f", r.getDistance().getValue()).concat("km"));
            groupInfo.setLatitude(String.valueOf(group.getLoc().getY()));
            groupInfo.setLongitude(String.valueOf(group.getLoc().getX()));
            groupInfo.setUserId(group.getUser_id());
            groupInfo.setInvisible(group.getInvisible());
            groupList.add(groupInfo);
        }
        //查询群组人数
        List<Long> groupIds = groupList.stream().map(GroupInfo::getGroupId).collect(Collectors.toList());
        List<CommonCount> res = groupMemberMapper.getMembersCountByGroupIds(groupIds);
        Map<Long, Integer> groupMemberCountMap = res.stream().collect(Collectors.toMap(CommonCount::getId, CommonCount::getCount));
        for (GroupInfo info : groupList) {
            Integer count = groupMemberCountMap.get(info.getGroupId());
            info.setMemberNumber(count == null ? 0 : count);
        }
        List<GroupInfo> joinedGroup = groupMapper.getMyGroup(userId);
        Set<Long> groupIdList = new TreeSet<>();
        for (GroupInfo groupInfo : joinedGroup) {
            groupIdList.add(groupInfo.getGroupId());
        }
        for (GroupInfo groupInfo : groupList) {
            if (groupIdList.contains(groupInfo.getGroupId())) {
                groupInfo.setHasJoined(true);
            } else {
                groupInfo.setHasJoined(false);
            }
        }
        return groupList;
    }

    /**
     * 申请进群
     *
     * @param dto
     * @return
     */
    /**
     * @Updateby:LiangWu
     * @Date: 2019/4/28 17:08
     * @Description:申请之后保存备注和审核状态入库
     */
    @Override
    public boolean applyGroup(ApplyGroupDto dto) {

        UserInfo userInfo = GlobalController.getNowUser();

        GroupNotice groupNotice = new GroupNotice();
        groupNotice.setUserId(userInfo.getId());
        groupNotice.setGroupId(dto.getGroupId());
        groupNotice.setCreatedTime(System.currentTimeMillis() / 1000);
        groupNotice.setMessage(dto.getMessage());
        groupNotice.setType(0);
        //查询用户是否已申请但未通过，是的话则抛异常
        GroupNotice gn = groupMemberMapper.selectIsApply(groupNotice);
        if (gn == null) {
            groupMemberMapper.insertApplyGroupNotice(groupNotice);
        } else if (gn.getType() == 0) {
            throw new UserException(StatusCode.APPLY_IS_SUBMIT);
        } else if (gn.getType() == 1) {
            throw new UserException(StatusCode.IN_GROUP);
        } else if (gn.getType() > 1) {
            groupMemberMapper.insertApplyGroupNotice(groupNotice);
        }

        //查询这批用户是否是已经存在群成员表中，如果已存在，把状态改成正常，如果不存在则插入
        Example selectExample = new Example(GroupMember.class);
        selectExample.createCriteria()
                .andCondition("group_id = " + dto.getGroupId())
                .andCondition("user_id = " + userInfo.getId());
        GroupMember groupMember = groupMemberMapper.selectOneByExample(selectExample);
        if (groupMember != null) {
            return true;
        }

        GroupMember insertGroupMember = new GroupMember();
        insertGroupMember.setGroup_id(dto.getGroupId());
        //updateTime:4/28 添加留言和状态入库
        insertGroupMember.setMessage(dto.getMessage());
        insertGroupMember.setIs_allow(0);

        insertGroupMember.setUser_id(userInfo.getId());
        insertGroupMember.setCreatedTime(Instant.now().getEpochSecond());
        insertGroupMember.setUpdated_time(Instant.now().getEpochSecond());
        return (groupMemberMapper.insertSelective(insertGroupMember) > 0);

    }


    /**
     * 禁言
     *
     * @param dto
     * @return
     */
    @Override
    public boolean ban(BanDto dto) {
        //判断是否是群主
        UserInfo userInfo = GlobalController.getNowUser();
        Group group = groupMapper.selectByPrimaryKey(dto.getGroupId());
        if (!group.getId().equals(userInfo.getId())) {
            throw new UserException(StatusCode.FORBIDDEN);
        }
        return groupMemberMapper.ban(dto.getGroupId(), userInfo.getId(), Instant.now().getEpochSecond()) > 0;
    }

    double[][] pointArray = {{39.9097728, 116.4001922}, {31.2175452, 121.5006593},
            {23.0595119, 113.2800127}, {22.5664787, 114.0600688}, {32.0406959, 118.7951800},
            {30.2768733, 120.1705295}, {30.6556517, 104.0707535}, {29.5531531, 106.5378512},
            {30.5332596, 114.3030931}, {31.3160952, 120.6092581}, {31.5758960, 120.3023402}
    };

    @Override
    public boolean sysnGroup(Integer startId, Integer endId) {
        Example query = new Example(Group.class);
        query.createCriteria()
                .andBetween("id", startId, endId);
        List<Group> groupList = groupMapper.selectByExample(query);
        System.out.println("group查询的结果为：" + (groupList == null ? 0 : groupList.size()));
        List<GroupEntity> groupEntitys = new ArrayList<>();
        for (Group group : groupList) {
            GroupEntity groupEntity = new GroupEntity();
            BeanUtils.copyProperties(group, groupEntity);
            int random = new Random().nextInt(10);
            double[] point = pointArray[random];
            GeoJsonPoint loc = new GeoJsonPoint(point[1], point[0]);
            groupEntity.setLoc(loc);
            groupEntity.setInvisible(0);
            groupEntity.setIntroduction("");
            groupEntitys.add(groupEntity);
        }
        groupRepository.saveAll(groupEntitys);
        return true;
    }

    /**
     * @Author:LiangWu
     * @Date: 2019/4/30 14:39
     * @Description:审核入群
     */
    @Override
    public boolean allowApply(AllowApplyDto allowApplyDto) {

        //当前用户是否管理员
        UserInfo user = GlobalController.getNowUser();
        GroupMember gm = new GroupMember();
        gm.setUser_id(user.getId());
        gm.setGroup_id(allowApplyDto.getGroupId());
        if (groupMapper.isManager(gm) == 0) {
            throw new UserException(StatusCode.REVIEWER_IS_NOT_MANAGER);
        }
        //修改时审核是否已被其他管理员审核
        if (groupMapper.validation(allowApplyDto) == 0) {
            GroupMember groupMember = new GroupMember();
            groupMember.setGroup_id(allowApplyDto.getGroupId());
            groupMember.setUser_id(allowApplyDto.getUserId());
            groupMember.setIs_allow(allowApplyDto.getIsAllow());
            groupMember.setReviewer(user.getId());
            groupMapper.updateByGroupIdAndUserId(groupMember);

            GroupNotice groupNotice = new GroupNotice();
            groupNotice.setHandlerId(user.getId());
            groupNotice.setGroupId(allowApplyDto.getGroupId());
            groupNotice.setCreatedTime(System.currentTimeMillis() / 1000);
            groupNotice.setType(allowApplyDto.getIsAllow());
            groupNotice.setUpdatedTime(System.currentTimeMillis() / 1000);
            groupMapper.updateGroupNotice(groupNotice);
            return true;
        } else {
            throw new UserException(StatusCode.APPLY_HAD_BE_HANDLED);
        }

    }

    //查看申请进群信息
    @Override
    public List<GroupMember> applyRecord(Long groupId) {
        return (groupMapper.selectByGroupIdAndIsAllow(groupId));
    }

//    /**
//     * @Author:LiangWu
//     * @Date: 2019/5/6 10:57
//     * @Description:解散群
//    */
//    @Override
//    public boolean dismiss(Long id) {
//        /**
//         *检验是否群主
//         */
//        Long userId = GlobalController.getNowUser().getId();
//        if(groupMapper.checkGroupOwner(id,userId)==0){
//            return false;
//        }
//        Long nowTime = System.currentTimeMillis()/1000;
//        groupMapper.dismissGroup(id,nowTime);
//        return true;
//    }
}
